package com.sky.admin.service.impl;

import com.sky.admin.domain.vo.BusinessDataVO;
import com.sky.admin.domain.vo.SalesTop10ReportVO;
import com.sky.admin.domain.vo.TurnoverReportVO;
import com.sky.admin.service.ReportService;
import com.sky.admin.service.WorkspaceService;
import com.sky.api.client.TradeFeignClient;
import com.sky.api.client.UserFeignClient;
import com.sky.api.domain.dto.DataOverViewQueryDTO;
import com.sky.api.domain.dto.GoodsSalesDTO;
import com.sky.api.domain.entity.Orders;
import com.sky.api.domain.vo.OrderReportVO;
import com.sky.api.domain.vo.UserReportVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author toki
 */
@Service
@RequiredArgsConstructor
//@EnableFeignClients(clients = {TradeFeignClient.class, UserFeignClient.class})
public class ReportServiceImpl implements ReportService {

    private final TradeFeignClient tradeFeignClient;
    private final UserFeignClient userFeignClient;
    private final WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            //日期计算，获得指定日期后1天的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 计算每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // LocalDateTime.of()获得指定某一天的开始时间和结束时间(LocalDateTime:年月日 时分秒 \ LocalDate:年月日)
            // 00:00:00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 23:59:59
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Double turnover = tradeFeignClient.sumByMap(beginTime, endTime, Orders.COMPLETED).getData();
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        final ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            // 日期计算，获得指定日期后1天的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //新增用户数
        List<Integer> newUserList = new ArrayList<>();
        //总用户数
        List<Integer> totalUserList = new ArrayList<>();
        // 计算每天的新增用户数和总用户数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 新增用户数
            Integer newUser = getUserCount(beginTime, endTime);
            // 总用户数
            Integer totalUser = getUserCount(null, endTime);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        //数据封装
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        final ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            // 日期计算，获得指定日期后1天的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        // 订单完成率
        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }
        // 数据封装
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = tradeFeignClient.getSalesTop10(beginTime, endTime).getData();
        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 根据时间区间统计用户数量
     *
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @return 用户统计报告
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
//        final Map<String, Object> map = new HashMap<>();
//        map.put("begin", beginTime);
//        map.put("end", endTime);
        return userFeignClient.countByMap(beginTime, endTime).getData();
    }

    /**
     * 根据时间区间统计指定状态的订单数量
     *
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @param status    订单状态
     * @return 指定状态的订单数量
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        return tradeFeignClient.countByMap(beginTime, endTime, status).getData();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        // 1.查询数据库,获取营业数据
        // 当前时间 减 30天的营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        // 当前时间 减 1天的营业数据
        LocalDate end = LocalDate.now().minusDays(1);
        // 调用业务层方法,获取营业数据,精确到时分秒
        final BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        // 2.通过POI将数据导入到Excel文件中
        final InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        ServletOutputStream out = null;
        XSSFWorkbook excel = null;
        try {
            if (in != null) {
                // 2.1 读取模板文件,创建新的Excel文件
                excel = new XSSFWorkbook(in);
                // 2.2 根据页名获取页
                final XSSFSheet sheet = excel.getSheet("Sheet1");
                // 2.3 根据模板,填充数据(获取单元格然后设值)
                sheet.getRow(1).getCell(1).setCellValue("制表日期：" + begin + "至" + end);

                XSSFRow row = sheet.getRow(3);
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(6).setCellValue(businessData.getNewUsers());
                row = sheet.getRow(4);
                row.getCell(2).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getUnitPrice());

                for (int i = 0; i < 30; i++) {
                    LocalDate date = begin.plusDays(i);
                    //准备单独每一天的明细数据
                    workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                    row = sheet.getRow(7 + i);
                    row.getCell(1).setCellValue(date.toString());
                    row.getCell(2).setCellValue(businessData.getTurnover());
                    row.getCell(3).setCellValue(businessData.getValidOrderCount());
                    row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                    row.getCell(5).setCellValue(businessData.getUnitPrice());
                    row.getCell(6).setCellValue(businessData.getNewUsers());
                }

                // 3.通过response输出到浏览器中
                out = response.getOutputStream();
                excel.write(out);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            if (out != null) {
                out.flush();
            }
            if (out != null) {
                out.close();
            }
            if (excel != null) {
                excel.close();
            }
            if (in != null) {
                in.close();
            }
        }

    }
}
